package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.common.R;
import com.itheima.untils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);

        //解析token
        String token = request.getHeader("x-token");
        //判断非空，否则解析会发生异常
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = JwtUtils.parseToken(token);
            String tokenId = (String) claims.get("id");
            String tokenLoginName = (String) claims.get("login_name");
            log.info("tokenId：{}===tokenLoginName：{}", tokenId, tokenLoginName);

            if (StringUtils.isNotEmpty(tokenId) && StringUtils.isNotEmpty(tokenLoginName)) {
                log.info("检验通过");
                return true;
            }
        }
        //解析token
        String FrontToken = request.getHeader("token");
        if (StringUtils.isNotEmpty(FrontToken)) {
            log.info("检验通过");
            return true;
        }

        response.getWriter().write(JSON.toJSONString(R.error("未登录")));
        return false;
    }
}
